import { ISMEventData } from "../../GameLogic";
import GCNetwork from "../../network/GCNetwork";
import OptionItemComponent from "./OptionItemComponent";
import ResultTipComponent from "./ResultTipComponent";
import ResultWnd from "./ResultWnd";


const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu('classic/ClassicComponent')
export default class ClassicComponent extends cc.Component {

  @property(cc.Sprite)
  questionSpr: cc.Sprite = null;

  @property([OptionItemComponent])
  optionList: OptionItemComponent[] = [];

  @property(cc.Node)
  classicContent: cc.Node = null;

  @property(ResultTipComponent)
  resultTip: ResultTipComponent = null;

  @property(ResultWnd)
  resultWnd: ResultWnd = null;


  resetUI() {
    this.questionSpr.spriteFrame = null;
    this.optionList.forEach(item => {
      item.node.active = false;
    });
  }

  initUI(pic: string, options: string[]) {

    // const bundle = cc.assetManager.getBundle('game');
    // const frame = bundle.get<cc.SpriteFrame>(`fruits/${pic}`, cc.SpriteFrame);

    this.questionSpr.node.active = false;
    const host = GCNetwork.getUrl();
    cc.assetManager.loadRemote(`${host}/games/images/${pic}.png`, (err, tex: cc.Texture2D) => {
      if (!cc.isValid(this.node)) return;

      if (!err) {
        this.questionSpr.node.active = true;

        const spf = new cc.SpriteFrame(tex);
        this.questionSpr.spriteFrame = spf;

        const { height } = spf.getRect();

        this.questionSpr.sizeMode = cc.Sprite.SizeMode.RAW;
        this.questionSpr.node.scale = 280 / height;
      } else {
        cc.error(err);
      }
    });

    const len = options.length;
    for (let i = 0; i < this.optionList.length; i++) {
      const opItem = this.optionList[i];
      opItem.node.active = i < len;

      if (i < len) {
        opItem.initUI(options[i]);
      }
    }
  }

  onOptionItemClicked(_: cc.Event.EventTouch, answer: string) {
    const evt = new cc.Event.EventCustom('sm-event', true);

    const data: ISMEventData = {
      type: 'answer',
      res: answer
    };

    evt.setUserData(data);
    this.node.dispatchEvent(evt);
  }

  onCollectBtnClicked() {
    const evt = new cc.Event.EventCustom('sm-event', true);

    const data: ISMEventData = {
      type: 'collect'
    }
    evt.setUserData(data);

    this.node.dispatchEvent(evt);
  }


  async moveToLeft() {
    const node = this.classicContent;

    return new Promise((resolve, _) => {
      cc.tween(node)
        .by(0.3, { x: -600 }, { easing: 'sineIn' })
        .call(() => {
          resolve(null);
        })
        .start();
    })
  }

  async moveToRight() {
    const node = this.classicContent;

    return new Promise((resolve, _) => {
      cc.tween(node)
        .set({ x: 600, active: true })
        .by(0.3, { x: -600 }, { easing: 'sineIn' })
        .call(() => {
          resolve(null);
        })
        .start();
    })
  }

}
